package com.hotel.controller;

import com.anji.captcha.util.AESUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotel.domain.SysUser;
import com.hotel.service.MailService;
import com.hotel.service.SysUserService;
import com.hotel.util.Constant;
import com.hotel.util.MD5Util;
import com.hotel.util.R;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.MessagingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@RestController
public class LoginController {


    @Autowired
    private SysUserService service;

    @Autowired
    private MailService mailService;

    @GetMapping({"/", "/login"})
    public ModelAndView login(){
        ModelAndView mv = new ModelAndView("login");
        return mv;
    }

    @GetMapping({"/email"})
    public ModelAndView email(){
        ModelAndView mv = new ModelAndView("email");
        return mv;
    }

    @PostMapping({"/email"})
    public R sendEmail(String email, HttpSession session) throws MessagingException {
        // 根据邮箱查询用户, 如果用户存在，发送邮件
        int code = mailService.sendLoginCodeEmail(email);
        // 保存验证码到 session
        session.setAttribute(Constant.LOGIN_CODE, code);
        return R.ok(email);
    }



    @PostMapping("/login")
    public R login(@RequestBody SysUser user, HttpServletResponse response, HttpSession session) throws Exception {
        // 密码 AES 解密
        String pass = AESUtil.aesDecrypt(user.getPassword(), user.getKey());
        user.setPassword(pass);
        // 根据传入的用户名和密码查询用户
        SysUser one = service.login(user);

        if (one != null){
            if (user.getRememberMe() != null && user.getRememberMe()){
                // "记住我"功能
                extracted(user, response, pass);
            }
            // 登录成功，将用户信息存入 session
            session.setAttribute(Constant.LOGIN_USER, one);
            // 登录成功，重定向到首页
            return R.ok("登录成功", "/index");
        } else {
            return R.fail("用户名或密码错误");
        }
    }

    private static void extracted(SysUser user, HttpServletResponse response, String pass) throws Exception {
        /*
         记住我功能：7天免登录如何实现？
         */
        //1.生成一个cookie，存储用户名，密码。
        String enUsername = AESUtil.aesEncrypt(user.getUsername(), Constant.REMEMBER_ME_AES_KEY);
        String enPass = AESUtil.aesEncrypt(pass, Constant.REMEMBER_ME_AES_KEY);
        //2. 用 AES加密，然后使用 -- 分隔
        String value = enUsername + Constant.REMEMBER_ME_COOKIE_SPLIT_CHAR + enPass;
        Cookie cookie = new Cookie(Constant.REMEMBER_ME_COOKIE_NAME, value);
        //3. 设置cookie的有效期为7天
        cookie.setMaxAge(60 * 60 * 24 * 7);
        //4. 设置cookie的作用域为根目录
        cookie.setPath("/");
        //5.将cookie添加到响应头中
        response.addCookie(cookie);
    }

    @GetMapping("/index")
    public ModelAndView index(@SessionAttribute(value = Constant.LOGIN_USER) SysUser user){
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("name", user.getName());
        return modelAndView;
    }

    @GetMapping("/logout")
    public ModelAndView logout(HttpSession session, HttpServletResponse response){
        // 退出登录，删除session中的用户信息
        session.removeAttribute(Constant.LOGIN_USER);
        // 退出登录，删除cookie
        Cookie cookie = new Cookie(Constant.REMEMBER_ME_COOKIE_NAME, "");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return new ModelAndView("redirect:/login");
    }
}